import os
import time
import glob
from openpyxl import load_workbook
from config.settings import get_config
from base.base_page import BasePage


class Excel_data_extraction(BasePage):
    def __init__(self, driver, device_type, logger=None):
        super().__init__(driver, device_type, logger=logger)
        self.driver = driver
        self.config = get_config(device_type)

    def wait_for_new_excel(self, timeout=30):
        """等待新Excel文件下载完成"""
        start_time = time.time()
        existing_files = set(glob.glob(os.path.join(self.config.download_dir, "*.xlsx")))

        while True:
            current_files = set(glob.glob(os.path.join(self.config.download_dir, "*.xlsx")))
            new_files = list(current_files - existing_files)

            if new_files:
                newest_file = max(new_files, key=os.path.getctime)
                # 验证文件完整性
                initial_size = os.path.getsize(newest_file)
                time.sleep(1)
                if os.path.getsize(newest_file) == initial_size:
                    self.logger.info("Excel文件已下载完成")
                    return newest_file

            if time.time() - start_time > timeout:
                raise TimeoutError(f"等待Excel文件下载超时（{timeout}秒）")

            time.sleep(1)

    def get_newest_excel(self, existing_files=None):
        """获取最新下载的Excel文件"""
        pattern = os.path.join(self.config.download_dir, "*.xlsx")
        all_files = glob.glob(pattern)

        if not all_files:
            return None

        if existing_files:
            new_files = list(set(all_files) - set(existing_files))
            if new_files:
                return max(new_files, key=os.path.getctime)
        return max(all_files, key=os.path.getctime)

    def parse_excel(self, file_path, params=None):
        """
        解析Excel文件内容
        :param file_path: Excel文件路径
        :param params: 解析参数配置，格式示例：
            {
                "sheet_name": "Sheet1",    # 工作表名称
                "start_row": 2,            # 起始行号（从1开始）
                "headers": ["姓名", "年龄"], # 列头验证（可选）
                "max_rows": 100            # 最大读取行数
            }
        :return: 包含字典的列表，每个字典对应一行数据
        """
        try:
            wb = load_workbook(filename=file_path, read_only=True, data_only=True)

            # 默认参数设置
            params = params or {}
            sheet_name = params.get("sheet_name", "Sheet1")
            start_row = params.get("start_row", 1)
            expected_headers = params.get("headers")
            max_rows = params.get("max_rows", 1000)

            # 获取工作表
            try:
                ws = wb[sheet_name]
            except KeyError:
                available_sheets = wb.sheetnames
                raise ValueError(f"工作表 '{sheet_name}' 不存在，可用工作表: {', '.join(available_sheets)}")

            # 读取数据
            results = []
            headers = []

            for row_idx, row in enumerate(ws.iter_rows(values_only=True), start=1):
                # 处理表头
                if row_idx == start_row - 1:
                    headers = [str(cell).strip() for cell in row]
                    if expected_headers:
                        if headers != expected_headers:
                            raise ValueError(f"列头不匹配，期望: {expected_headers}，实际: {headers}")
                    continue

                # 处理数据行
                if start_row <= row_idx <= start_row + max_rows:
                    row_data = {}
                    for col_idx, cell_value in enumerate(row):
                        header = headers[col_idx] if col_idx < len(headers) else f"Column{col_idx + 1}"
                        row_data[header] = cell_value
                    results.append(row_data)
                elif row_idx > start_row + max_rows:
                    break

            self.logger.info(f"成功读取 {len(results)} 行数据（工作表: {sheet_name}）")
            return results

        except Exception as e:
            self.logger.error(f"Excel解析失败: {str(e)}")
            raise
        finally:
            wb.close()